/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package org.luxor.generator.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.luxor.generator.service.SysGeneratorService;
import org.luxor.generator.utils.PageUtils;
import org.luxor.generator.utils.Query;
import org.luxor.generator.utils.R;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 代码生成器
 *
 * @author Mark sunlightcs@gmail.com
 */
@Api(tags = "代码生成器")
@Controller
@RequestMapping("/sys/generator")
public class SysGeneratorController {

    @Resource
    private SysGeneratorService sysGeneratorService;

    @ApiOperation("数据库表查询")
    @RequestMapping("/list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils pageUtil = sysGeneratorService.queryList(new Query(params));
        return R.ok().put("page", pageUtil);
    }

    @ApiOperation("生成代码")
    @RequestMapping("/code")
    public void code(String tables, HttpServletResponse response) throws IOException {
        byte[] data = sysGeneratorService.generatorCode(tables.split(","));
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

    @ApiOperation("生成文档")
    @RequestMapping("/word")
    public void word(String tables, HttpServletResponse response) throws IOException {
        byte[] data = sysGeneratorService.generatorWord(tables.split(","));
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"TableWord.doc\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/msword; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}
